
package zzh.com.kangkenuo;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebSettings;

import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.download.DownloadTask;
import com.lzy.okhttpserver.listener.DownloadListener;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.FileCallback;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.model.HttpHeaders;
import com.lzy.okhttputils.model.HttpParams;
import com.lzy.okhttputils.request.BaseBodyRequest;
import com.lzy.okhttputils.request.BaseRequest;
import com.lzy.okhttputils.request.GetRequest;
import com.lzy.okhttputils.request.PostRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import zzh.com.kangkenuo.newutlis.Encrypt;
import zzh.com.kangkenuo.newutlis.EventbusHelper;
import zzh.com.kangkenuo.newutlis.NetMsgEvent;


/**
 * 项目名称：
 * 类描述：
 * 创建人：
 * 创建时间：
 * 修改人：
 * 修改时间
 * 修改备注：
 */

public class PublicRequest {

    public static String TAG = "PublicRequest";

    public static Map<String, String> appParams() {
        long time = System.currentTimeMillis() / 1000;
        String CurrentTime = String.valueOf(time);
        String apikey = "KKN_201711" + "|" + CurrentTime;
        String md5_apikey = Encrypt.get32MD5Str(apikey);
        Map<String, String> urlParams = new HashMap<>();
        urlParams.put("ts", CurrentTime);
        urlParams.put("apikey", md5_apikey);
        urlParams.put("ApiSecret", "7eec4bb114a0e48e498d7d9c75829b45");
        return urlParams;
    }

    private static String getUserAgent() {
        String userAgent = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                userAgent = WebSettings.getDefaultUserAgent(MyApplication.getContext());
            } catch (Exception e) {
                userAgent = System.getProperty("http.agent");
            }
        } else {
            userAgent = System.getProperty("http.agent");
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }


    public static void doPostRequest(final String url, final Map<String, String> appParams,
                                     final Object type) {
        Map<String, String> addMap = appParams();
        addMap.putAll(appParams);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put("User-Agent", getUserAgent() + "HzResfine");
        OkHttpUtils.post(url)
                .params(addMap)
                .removeHeader("User-Agent")
                .headers(httpHeaders)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e("response", s);
                        if (TextUtils.isEmpty(s)) {
                            Log.e(TAG, "数据有误");
                            return;
                        }
                        try {
                            JSONObject object = new JSONObject(s);
                            NetMsgEvent env = new NetMsgEvent(object);
                            env.setMsgType(type);
                            EventbusHelper.post(env);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        Log.e(TAG, e.toString());
                    }

                });

    }

    public static void getFile(Context context) {
        final ProgressDialog dialog = new ProgressDialog(context);
        dialog.setTitle("正在下载...");
        dialog.setCancelable(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.show();



        DownloadManager.getInstance().addTask("kknt.app", "TAG",
                OkHttpUtils.get("http://openbox.mobilem.360.cn/index/d/sid/3960488")
                , new DownloadListener() {
                    @Override
                    public void onProgress(DownloadInfo downloadInfo) {
                        dialog.setProgress((int) (100 * downloadInfo.getProgress()));
                    }

                    @Override
                    public void onFinish(DownloadInfo downloadInfo) {

                    }

                    @Override
                    public void onError(DownloadInfo downloadInfo, String errorMsg, Exception e) {

                    }
                });

    }

    public static void postFile(String url, String head, String file, final String filename,
                                final String type) {

        try {
            File f = new File(file);
            OkHttpUtils
                    .post(url)
                    .params(appParams())
                    .params(head, f)
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                        }

                        @Override
                        public void onSuccess(String s, Call call, Response response) {

                        }
                    });
        } catch (Exception r) {
            r.printStackTrace();
        }
    }


    public static void laodingFile(final Context context, String s) {
        try {
            final ProgressDialog dialog = new ProgressDialog(context);
            dialog.setTitle("正在下载...");
            dialog.setCancelable(false);
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.show();
            OkHttpUtils.get("http://openbox.mobilem.360.cn/index/d/sid/3960488")
                    .execute(new FileCallback(Environment.getExternalStorageDirectory()
                            .getAbsolutePath(), "kknt_app.apk") {
                        @Override
                        public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                            Log.e("progress", currentSize + "-------" + totalSize + "---" + progress + "---" + networkSpeed);
                            dialog.setProgress((int) (100 * progress));
                        }

                        @Override
                        public void onSuccess(File file, Call call, Response response) {
                            installApk(context, file);
                            dialog.dismiss();
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
    * 取得文件大小*/

    public static long getFileSizes(File f) throws Exception {
        long s = 0;
        FileInputStream fis = new FileInputStream(f);
        s = fis.available();
        return s;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */

    public static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS);
        } else if (fileS < 1048576) {
//            fileSizeString = df.format((double) fileS / 1024);//K
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576);//+ "M"
        } else {
            fileSizeString = df.format((double) fileS / 1073741824);// + "G"
        }
        return fileSizeString;
    }

    /**
     * 安装apk
     *
     * @param context 上下文
     * @param file    APK文件
     */
    public static void installApk(Context context, File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  // N以上的申请权限实例
            Uri fileuri = FileProvider.getUriForFile(context, "zzh.com.kangkenuo.takephoto.fileprovider", file);
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(fileuri, "application/vnd.android.package-archive");
            context.startActivity(intent);
        } else {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            context.startActivity(intent);
        }
    }


}